package com.tuyan.aixiang.receiver;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.api.HttpClient;
import com.tuyan.aixiang.api.helper.ResultTransformer;
import com.tuyan.aixiang.api.helper.RxSchedulers;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.common.StorageKey;
import com.tuyan.aixiang.model.Event;
import com.tuyan.aixiang.util.Log;
import com.tuyan.aixiang.util.StorageUtil;

import org.greenrobot.eventbus.EventBus;

import androidx.core.app.NotificationCompat;
import io.reactivex.disposables.Disposable;

import static android.content.Context.NOTIFICATION_SERVICE;

public class MessageHandler {

    private static final String TAG = "MessageHandler";

    public static void onMessage() {
        onMessage(false);
    }

    public static void onMessage(Context context) {
        Log.d(TAG, "onMessage");
        MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.dingdong);

        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int vol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);
        if (StorageUtil.getInt(StorageKey.NOTICE_SOUND, Constant.NOTICE_SOUND_TYPE_DEFAULT) == Constant.NOTICE_SOUND_TYPE_DEFAULT) {
            mediaPlayer.setVolume(0.1f, 0.1f);
        } else {
            mediaPlayer.setVolume(1.0f, 1.0f);
        }
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            mediaPlayer.prepare();
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(mp -> {
            // restore origin volume
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0);
        });
        onMessage();
    }

    public static void buildNotification(Context context, CPushMessage message) {
        String title = message.getTitle();
        String content = message.getContent();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setPriority(Notification.VISIBILITY_PRIVATE)
                .setChannelId("2")
                .build();
        notification.contentIntent = buildClickContent(context, message);
        if (notificationManager != null) {
            notificationManager.notify(message.hashCode(), notification);
        }
        onMessage(context);
    }

    public static PendingIntent buildClickContent(Context context, CPushMessage message) {
        Intent clickIntent = new Intent();

        // TODO receiver action
        clickIntent.setAction("");
        //添加其他数据
        clickIntent.putExtra("message key", message);//将message放入intent中，方便通知自建通知的点击事件
        return PendingIntent.getService(context, 1, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    }


    public static void onMessage(boolean local) {

        if (!local) {
            StorageUtil.setBoolean(StorageKey.HAS_NEW_MSG, true);
            EventBus.getDefault().post(new Event(Event.EventType.NEW_MSG));
        }


        if (MainApplication.isForeground()) {

//            Disposable disposable = HttpClient.getNotiMsg().unreadCount().compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
//                    .subscribe(r -> {
//                        if (null != r.get()) ;
//                        AppData.setMsgCount(r.get());
//                    }, t -> {
//
//                    });
//
//            Disposable disposable = HttpClient.getNotice().noticeList(M.m().put("dr_status", 1).put("dr_model", Constant.MODEL_CAMERA))
//                    .compose(RxSchedulers.io_main())
//                    .compose(ResultTransformer.handleResult())
//                    .subscribe(data -> {
//                        PageUtils page = data.get();
//                        AppData.setCameraNoticeCount(page.getCount());
//                    }, throwable -> {
//
//                    });
//
//            Disposable disposable2 = HttpClient.getNotice().noticeList(M.m().put("dr_status", 1).put("dr_model", Constant.MODEL_ALARM))
//                    .compose(RxSchedulers.io_main())
//                    .compose(ResultTransformer.handleResult())
//                    .subscribe(data -> {
//                        PageUtils page = data.get();
//                        AppData.setAlarmNoticeCount(page.getCount());
//                    }, throwable -> {
//
//                    });

            Disposable disposable = HttpClient.getNotice().noticeCount()
                    .compose(RxSchedulers.io_main())
                    .compose(ResultTransformer.handleResult())
                    .subscribe(data -> {
                        AppData.setNoticeCount(data.get());
                    }, throwable -> {});


        }
    }
}
